﻿using System;

namespace ApiScannerShell
{
    class EnumMapping<TModel, TEnum> : SimpleMapping<TModel>
    {
        private readonly TEnum _EnumValue;

        public EnumMapping(string propertName, TEnum enumValue): base(propertName)
        {
            _EnumValue = enumValue;
        }

        public override object LoadValue(TModel model)
        {
            var value = Convert.ToInt64(base.LoadValue(model));
            var mask = Convert.ToInt64(_EnumValue);
            return (value & mask) == mask;
        }

        public override void SetValue(object value, TModel model)
        {
            var oldValue = Convert.ToInt64(base.LoadValue(model));
            var mask = Convert.ToInt64(_EnumValue);
            if ((bool) value)
            {
                oldValue |= mask;
            }
            else
            {
                oldValue &= ~mask;
            }
            var newValue = Enum.ToObject(typeof (TEnum), oldValue);
            base.SetValue(newValue, model);
        }
    }
}